﻿package src.util
{
	
	/**
	* 
	* Reliability project
	* -----------------------
	* @author  Dmitrij Boycov
	* @mail    dmitry.boycov@gmail.com
	* @date    April 27, 2010
	* @version 1
	* 
	*/
	
	import flash.utils.Dictionary; 
	import flash.utils.ByteArray;
	//
	import src.entity.IEntity;
	
	public class Container {
		
		private var dict:Dictionary = new Dictionary();// true - delete elements
		private var autoIncrementID:Number = 1;
		private var cursor:Number = 1;
		
		public function Container(){			
		}
		
		public function add(el:IEntity) {
			if(el != null){
				this.dict[this.autoIncrementID] = el;
				el.setId(this.autoIncrementID);
				this.autoIncrementID++;
			}
		}
		
		public function remove(key){
			delete dict[key];
		}
		
		public function getById(key) {			
			if (dict[key]!= null) {
				return dict[key];
			}
			return null;
		}
		
		public function first() {
			this.cursor = 1;
		}	
		
		public function getNext() {
			if (cursor < 1|| cursor > this.autoIncrementID) return null;
			for (var i = this.cursor; i <= this.autoIncrementID; i++ ) {				
				if (dict[i] != null) {
					this.cursor = i+1;
					return dict[i];
				}				
			}
			this.cursor = i+1;
			return null;
		}
		
		public function containerToDict() {
			this.first();
			var dn:Dictionary = new Dictionary();
			var a = this.getNext();			
			while (a != null) {
				var d = a.getDictDesc();				
				dn[d.id] = d;
				a = this.getNext();
			}		
			return dn;
		}
		
		public function length():Number {			
			return Utils.sizeDict(dict);			
		}		
		
		public function toXML(root = "container"):String {
			var str = "<" + root + ">";
			this.first();			
			var a = this.getNext();			
			while (a != null) {
				str += a.toXML();				
				a = this.getNext();
			}	
			str += "</" + root + ">";
			return str;
		}
		
		
	}
	
}